<?php

namespace app\admin\controller\hf;

use app\api\controller\Babaohui;
use app\common\controller\Backend;
use think\Db;
use app\admin\model\caiwu\Money as moneylog;
use app\common\controller\MyHelp;

/**
 * 话费商品
 *
 * @icon fa fa-circle-o
 */
class Qdgoods extends Backend
{

    /**
     * Qdgoods模型对象
     * @var \app\admin\model\hf\Qdgoods
     */
    protected $model = null;
    protected $noNeedRight = ['set'];
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\hf\Qdgoods;
        $this->view->assign("typeList", $this->model->getTypeList());
        $this->view->assign("yysList", $this->model->getYysList());
        $this->view->assign("statussList", $this->model->getStatussList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->where('statuss', '1')
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $row) {
                $row->visible(['id', 'mz', 'title', 'cb', 'price', 'price_h5', 'type', 'yys', 'statuss', 'forbid']);
            }
            $admin = db::table('fa_admin')->where('id', $this->auth->id)->find();
            $ddd = $list->items();
            foreach ($ddd as $key => $value) {

                $zzzz =  MyHelp::getPriceNew($admin, $value['id']);
                // $zzzz =  MyHelp::getPrice($admin, $value['cb'], $value['mz']);


                $ddd[$key]['price'] = $zzzz['price'];
                $ddd[$key]['price_h5'] = $zzzz['price_h5'];
                $ddd[$key]['cb'] = 0;
            }
            $result = array("total" => $list->total(), "rows" => $ddd);

            return json($result);
        }
        $admin = db::table('fa_admin')->where('id', $this->auth->id)->find();
        $key = $admin['key'];
        $this->assign('key', $key);
        return $this->view->fetch();
    }
    /**
     * 提交订单
     */
    public  function sub($ids)
    {
        $row = $this->model->get($ids);
        $mobile = $this->request->request('mobile');

        if ($this->request->isPost()) {
            $mobile = str_replace(' ', '', $mobile);
            if (strlen($mobile) != 11) {
                return $this->error('手机号格式有误');
            }
            if ($row['statuss'] == '2') {
                return $this->error('禁售状态，无法下单');
            }
            $admin_id = $this->auth->id;
            $goods = $row;
            $sxf = 0; //微信手续费
            $admin = db::table('fa_admin')->where('id', $admin_id)->find();

            $zzzz =  MyHelp::getPriceNew($admin, $goods['id']);

            $lr = $zzzz['lr']; //实际用户价格
            $price = $zzzz['price']; //实际用户价格

            $zzlr = 0; //面值的0.5%
            $lirun = 0; //平台利润

            $money = $admin['money'];
            if ($money < $price) {
                return $this->error('余额不足');
            }
            $Babaohui = new Babaohui();
            $mobileInfo = $Babaohui->getYys1($mobile);
            $mobileInfo_arr = json_decode($mobileInfo, true);
            if (!isset($mobileInfo_arr['result']['Province'])) {
                return $this->error('系统异常或手机号有误');
            }
            $Province = $mobileInfo_arr['result']['Province'];
            $City = $mobileInfo_arr['result']['City'];
            $Isp = $mobileInfo_arr['result']['Isp'];
            if ($Isp == '中国移动') {
                $yys = '1';
                $image = 'https://cdn.8nit.cn/uploads/20240101/eb0722ebcea3427f48c4dd8fada552a1.png';
            } elseif ($Isp == '中国联通') {
                $yys = '2';
                $image = 'https://cdn.8nit.cn/uploads/20240101/a09d4985e64f735f69f51dfe7e13d1be.png';
            } elseif ($Isp == '中国电信') {
                $yys = '3';
                $image = 'https://cdn.8nit.cn/uploads/20240101/fce2efbd9e7765b73cd9aed2cb6ea839.png';
            } else {
                $this->error('不支持的运营商');
            }
            $orderno = 'HF' . date("Ymdhis")  . mt_rand(1000000, 99999999);


            $data = [
                'admin_id' => $admin_id,
                'orderno' => $orderno,
                'account' => $mobile,
                'createtime' => time(),
                'update_time' => time(),
                'goodsid' => $ids,
                'code' => $goods['code'],
                'mz' => $goods['mz'],
                'user_id' => 0,
                'province' => $Province,
                'city' => $City,
                'yys' => $yys,
                'cztype' => $goods['type'],
                'lirun' => $lirun,
                'price' => $price,
                'cbprice' => $goods['cb'],
                'sxf' => $sxf,
                'zzlr' => $zzlr,
                'from' => '2',
                'image' => $image,
                'title' => $goods['title'],
                'ordernoO' => $orderno,
                'lr_arr' => json_encode($lr),
                'api' => $goods['api']
            ];
            Db::table('fa_hf_order')->insert($data);
            $new_money = round($money - $price, 2);
            Moneylog::create(['admin_id' => $admin_id, 'type' => '2', 'money' => $price * -1, 'before' => $money, 'after' => $new_money, 'memo' => '后台下单', 'type1' => 1, 'orderPc' => $orderno]);

            db::table('fa_admin')->where('id', $admin_id)->update(['money' => $new_money]);

            $Babaohui = new Babaohui();
            $rst =  $Babaohui->addOrderHF1($orderno, $mobile, $goods['code'], $goods['type'], $goods['api']);

            if ($rst['code'] == 1) {
                Db::table('fa_hf_order')->where('orderno', $orderno)->update(['statuss' => '2', 'remark' => '充值中', 'api_order' => $rst['order']]);
                return $this->success('提交成功');
            } else {
                Db::table('fa_hf_order')->where('orderno', $orderno)->update(['statuss' => '4', 'remark' => '失败退款:' . $rst['msg'], 'ccccc' => 100]);
                $before = $new_money;
                $new_money = $admin['money'];
                Moneylog::create(['admin_id' => $admin_id, 'type' => '2', 'money' => $price, 'before' => $before, 'after' => $new_money, 'memo' => '后台下单退款', 'type1' => 2, 'orderPc' => $orderno]);

                db::table('fa_admin')->where('id', $admin_id)->update(['money' => $new_money]);
                return $this->error('提交失败：' . $rst['msg']);
            }
        }

        $admin_id = $this->auth->id;

        $admin = db::table('fa_admin')->where('id', $admin_id)->find();
        $goods = $row;
        $zzzz =  MyHelp::getPriceNew($admin, $goods['id']);

        $lr = $zzzz['lr']; //实际用户价格
        $price = $zzzz['price']; //实际用户价格
        $row['price'] = $price;

        $this->assign('row', $row);
        return $this->view->fetch();
    }
    /**
     * 加价
     */
    public  function set()
    {
        $money = $this->request->request('money');

        $admin = db::table('fa_admin')->where('id', $this->auth->id)->find();
        if ($this->request->isPost()) {
            if ($money < 0) {
                return $this->error('加价金额有误');
            }
            if ($money > 2) {
                return $this->error('加价金额最大只能是2');
            }

            db::table('fa_admin')->where('id', $this->auth->id)->update(['h5_add' => $money]);
            return $this->success('修改成功');
        }

        //平台 A B h5
        //平台 A h5
        $this->assign('row', $admin);
        return $this->view->fetch();
    }
    public function priceset()
    {
        $sku =  db::table('fa_hf_goods')->select();
        $admin = db::table('fa_admin')->where('id', $this->auth->id)->find();

        if ($this->request->isPost()) {
            $params = $this->request->post('row/a');

            foreach ($sku as $key1 => $value1) {
                if (!isset($params['add' . $value1['id']])) {
                    return $this->error('参数有误');
                }
                $addrate = $params['add' . $value1['id']];
                // return  $addrate;
                if ($addrate < 0) {
                    return $this->error('金额必须大于0');
                }

                $zz =  db::table('fa_hf_goods_addprice')->where('admin_id', $this->auth->id)->where('goodsid', $value1['id'])->where('type', 1)->find();
                if ($zz) {
                    db::table('fa_hf_goods_addprice')->where('id', $zz['id'])->update(['add' => $addrate]);
                } else {
                    db::table('fa_hf_goods_addprice')->insert(['add' => $addrate, 'goodsid' => $value1['id'], 'admin_id' => $this->auth->id, 'type' => 1]);
                }
            }
            return $this->success('修改成功');
        }

        foreach ($sku as $key1 => $value1) {
            $zzzz =  MyHelp::getPriceNew($admin, $value1['id']); //直接推广者
            $myprice = $zzzz['price']; //成本价
            $zz =  db::table('fa_hf_goods_addprice')->where('admin_id', $this->auth->id)->where('goodsid', $value1['id'])->where('type', 1)->find();
            if ($zz) {
                $sku[$key1]['add'] = $zz['add'];
            } else {
                $sku[$key1]['add'] = 0;
            }
            $sku[$key1]['myprice'] = $myprice;
        }
        $this->assign('zz', $sku);
        return $this->view->fetch();
    }
}
